package org.ruanjj.net;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class IpTcpMain {
    public static void main(String[] args) throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println(inetAddress);
    }


    //客户端
    @Test
    public void client() throws IOException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        int port = 8980;

        try(  Socket socket = new Socket(inetAddress,port);
              OutputStream os = socket.getOutputStream()){
            os.write("你好，我是客户端，准备发送请求".getBytes());
        }

        System.out.println("客户端请求结束");
    }


    @Test
    //服务器端
    public void server() {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        BufferedInputStream bi = null;

        try{
            int port = 8980;
            serverSocket = new ServerSocket(port);
            accept = serverSocket.accept();
            System.out.println(accept.getInetAddress().getHostAddress());
            is = accept.getInputStream();
            bi = new BufferedInputStream(is);

            byte[] b = bi.readAllBytes();
            String txt = new String(b);
            System.out.println(txt);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(bi != null){
                try {
                    bi.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if(accept != null){
                try {
                    accept.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        System.out.println("我是服务器端已经成功收到消息了");
    }
}
